import React, { useState, useRef, useLayoutEffect, useImperativeHandle, forwardRef, useEffect } from 'react';
import { View, StyleSheet, Alert, TouchableOpacity, ActivityIndicator, Text, TextInput, KeyboardAvoidingView, Platform, ScrollView, PermissionsAndroid } from 'react-native';
import { launchImageLibrary, ImagePickerResponse, MediaType } from 'react-native-image-picker';
import { CreateCardRequest } from '../types/Card';
import CardApiNative from '../services/CardApiNative';
import { useNavigation, useRoute } from '@react-navigation/native';
import RNFS from 'react-native-fs';
import SecureImageView from '../components/SecureImageView';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import ImageCropPicker from 'react-native-image-crop-picker';
import { useActionSheet } from '@expo/react-native-action-sheet';
import DouBaoTTSService from '../services/DouBaoTTSService';
import Sound from 'react-native-sound';



// 生成唯一ID的函数
const generateUniqueId = (): string => {
  const timestamp = Date.now();
  const random = Math.floor(Math.random() * 10000);
  return `${timestamp}_${random}`;
};

// CardEditor 逻辑合并
export interface CardEditorRef {
  save: () => void;
}

const CardEditor = forwardRef<CardEditorRef, {
  onSave: (cardData: CreateCardRequest) => void;
  onCancel: () => void;
  loading?: boolean;
  card?: any; // 使用 any 类型来支持编辑模式下的完整卡片对象
  onTTSConfigMissing?: () => void; // 新增 TTS 配置缺失回调
}>(({ onSave, onCancel, loading = false, card, onTTSConfigMissing }, ref) => {
  const [title, setTitle] = useState('');
  const [backText, setBackText] = useState('');
  const [imageUri, setImageUri] = useState('');
  const [imageLoading, setImageLoading] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const [isSynthesizing, setIsSynthesizing] = useState(false);
  const [currentSound, setCurrentSound] = useState<Sound | null>(null);
  const [currentAudioText, setCurrentAudioText] = useState('');
  const [currentAudioPath, setCurrentAudioPath] = useState('');
  const { showActionSheetWithOptions } = useActionSheet();

  // 格式化TTS错误信息
  const formatTTSError = (error: any): string => {
    let errorMessage = '语音合成失败';
    
    // 提取错误信息
    if (error && typeof error === 'object') {
      if (error.message) {
        errorMessage += `: ${error.message}`;
      } else if (error.toString) {
        errorMessage += `: ${error.toString()}`;
      }
    } else if (typeof error === 'string') {
      errorMessage += `: ${error}`;
    }
    
    // 添加检查建议
    errorMessage += '\n\n请检查：\n1. appid 和 token 是否正确\n2. 网络连接是否正常\n3. 豆包TTS服务是否可用';
    
    return errorMessage;
  };

  // 请求存储权限
  const requestStoragePermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
          {
            title: "存储权限",
            message: "应用需要访问您的相册来选择图片",
            buttonNeutral: "稍后询问",
            buttonNegative: "取消",
            buttonPositive: "确定"
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('存储权限已授予');
          return true;
        } else {
          console.log('存储权限被拒绝');
          Alert.alert('权限被拒绝', '需要存储权限才能选择图片');
          return false;
        }
      } catch (err) {
        console.warn(err);
        return false;
      }
    }
    return true; // iOS 不需要这个权限
  };

  // 请求相机权限
  const requestCameraPermission = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.CAMERA,
          {
            title: "相机权限",
            message: "应用需要访问您的相机来拍照",
            buttonNeutral: "稍后询问",
            buttonNegative: "取消",
            buttonPositive: "确定"
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('相机权限已授予');
          return true;
        } else {
          console.log('相机权限被拒绝');
          Alert.alert('权限被拒绝', '需要相机权限才能拍照');
          return false;
        }
      } catch (err) {
        console.warn(err);
        return false;
      }
    }
    return true; // iOS 不需要这个权限
  };

  useEffect(() => {
    if (card) {
      setTitle(card.title || '');
      setBackText(card.back_text || '');
      setImageUri(card.front_image || '');
      setCurrentAudioText(card.audio_text || '');
      setCurrentAudioPath(card.audio_path || '');
    }
  }, [card]);

  // 清理音频资源
  useEffect(() => {
    return () => {
      if (currentSound) {
        currentSound.release();
      }
    };
  }, [currentSound]);

  // 试听音频
  // 检查文本是否有修改
  const hasTextChanged = () => {
    const newText = `${title.trim()}。${backText.trim()}`;
    return newText !== currentAudioText;
  };

  // 检查音频文件是否存在
  const checkAudioFileExists = async (audioPath: string): Promise<boolean> => {
    try {
      if (!audioPath) return false;
      
      // 构建完整路径（使用外部存储目录）
      const fullPath = `${RNFS.ExternalDirectoryPath}/golang_data/${audioPath}`;
      const exists = await RNFS.exists(fullPath);
      console.log('📁 检查音频文件是否存在:', fullPath, exists);
      return exists;
    } catch (error) {
      console.error('❌ 检查音频文件失败:', error);
      return false;
    }
  };



  const handlePreviewAudio = async () => {
    if (!title.trim() && !backText.trim()) {
      Alert.alert('提示', '请先输入标题或背面文字');
      return;
    }

    if (isPlaying) {
      // 停止播放
      if (currentSound) {
        currentSound.stop();
        currentSound.release();
        setCurrentSound(null);
      }
      setIsPlaying(false);
      return;
    }

    if (isSynthesizing) {
      return; // 正在合成中，忽略点击
    }

    try {
      setIsSynthesizing(true);
      console.log('🎵 开始试听音频合成');

      const textToSynthesize = `${title.trim()}。${backText.trim()}`;
      
      // 检查是否有现有音频文件且文本未修改
      if (card?.audio_path && card?.audio_text === textToSynthesize) {
        const audioExists = await checkAudioFileExists(card.audio_path);
        if (audioExists) {
          console.log('📁 文本未修改，使用现有音频文件:', card.audio_path);
          
          // 构建完整音频路径（使用外部存储目录）
          const fullAudioPath = `${RNFS.ExternalDirectoryPath}/golang_data/${card.audio_path}`;
          
          // 播放现有音频
          const sound = new Sound(fullAudioPath, '', (error) => {
            if (error) {
              console.error('❌ 音频播放失败:', error);
              Alert.alert('播放失败', '无法播放音频文件');
              setIsPlaying(false);
              setIsSynthesizing(false);
              return;
            }
            
            console.log('✅ 音频加载成功，开始播放');
            setIsPlaying(true);
            setIsSynthesizing(false);
            
            sound.play((success) => {
              if (success) {
                console.log('✅ 音频播放完成');
              } else {
                console.error('❌ 音频播放失败');
              }
              setIsPlaying(false);
              sound.release();
              setCurrentSound(null);
            });
          });
          
          setCurrentSound(sound);
          return;
        }
      } else {
        console.log('📝 文本已修改或没有音频信息，需要重新合成');
      }
      
      // 需要重新合成音频
      console.log('🎵 开始试听音频合成');
      
      // 检查TTS配置
      try {
        // 先尝试从本地存储初始化TTS配置
        const initialized = await DouBaoTTSService.initializeTTSConfig();
        console.log('🔍 TTS配置初始化结果:', initialized);
        
        // 然后获取TTS配置
        const ttsConfig = await DouBaoTTSService.getTTSConfig();
        console.log('🔍 获取到的TTS配置:', ttsConfig);
        
        if (!ttsConfig.appid || !ttsConfig.token) {
          console.log('❌ TTS配置未设置，无法试听');
          Alert.alert(
            'TTS配置未设置',
            '请先在设置中配置语音合成的appid和token，否则无法试听音频',
            [
              { text: '取消', style: 'cancel' },
              { text: '去设置', onPress: () => {
                // 跳转到设置页面
                if (onTTSConfigMissing) {
                  onTTSConfigMissing();
                }
              }},
              { text: '以后再说', onPress: () => {
                // 用户选择跳过，不做任何操作
                console.log('📝 用户选择跳过TTS配置（试听）');
              }}
            ]
          );
          setIsSynthesizing(false);
          return;
        }
        console.log('✅ TTS配置已设置，可以试听');
      } catch (error) {
        console.error('❌ 检查TTS配置失败:', error);
        Alert.alert('错误', '检查TTS配置失败');
        setIsSynthesizing(false);
        return;
      }
      
      // 先初始化TTS配置
      await DouBaoTTSService.initializeTTSConfig();
      
      // 生成正式音频文件路径（统一使用时间戳+随机数确保唯一性）
      const audioId = generateUniqueId();
      const audioFileName = `audio_${audioId}.mp3`;
      const audioPath = `cards/${audioFileName}`;
      
      console.log('📁 音频文件路径:', audioPath);
      console.log('📝 合成文本:', textToSynthesize);
      
      // 调用豆包TTS合成音频
      const synthesizedAudioPath = await DouBaoTTSService.synthesizeAudio(
        textToSynthesize, 
        'doubao', 
        audioPath
      );
      
      console.log('✅ 试听音频合成成功:', synthesizedAudioPath);
      
      // 更新音频信息，以便下次试听时能直接使用
      if (card) {
        card.audio_path = synthesizedAudioPath;
        card.audio_text = textToSynthesize;
        console.log('📝 已更新音频信息:', { audio_path: synthesizedAudioPath, audio_text: textToSynthesize });
      }
      
      // 构建完整的音频文件路径用于播放（使用外部存储目录）
      const fullAudioPath = `${RNFS.ExternalDirectoryPath}/golang_data/${synthesizedAudioPath}`;
      console.log('📁 播放音频文件路径:', fullAudioPath);
      
      // 播放音频
      const sound = new Sound(fullAudioPath, '', (error) => {
        if (error) {
          console.error('❌ 音频播放失败:', error);
          Alert.alert('播放失败', '无法播放音频文件');
          setIsPlaying(false);
          setIsSynthesizing(false);
          return;
        }
        
        console.log('✅ 音频加载成功，开始播放');
        setIsPlaying(true);
        setIsSynthesizing(false);
        
        sound.play((success) => {
          if (success) {
            console.log('✅ 音频播放完成');
          } else {
            console.error('❌ 音频播放失败');
          }
          setIsPlaying(false);
          sound.release();
          setCurrentSound(null);
        });
      });
      
      setCurrentSound(sound);
      
    } catch (error) {
      console.error('❌ 试听音频合成失败:', error);
      const errorMessage = formatTTSError(error);
      Alert.alert('语音合成失败', errorMessage, [
        { text: '取消', style: 'cancel' },
        { text: '去设置', onPress: () => {
          // 跳转到设置页面
          if (onTTSConfigMissing) {
            onTTSConfigMissing();
          }
        }},
        { text: '以后再说', onPress: () => {
          // 用户选择跳过，不做任何操作
          console.log('📝 用户选择跳过TTS配置（试听）');
        }}
      ]);
      setIsSynthesizing(false);
    }
  };

  const selectImage = async () => {
    const options = ['拍照', '从相册选择', '取消'];
    showActionSheetWithOptions(
      {
        options,
        cancelButtonIndex: 2,
      },
      (buttonIndex) => {
        if (buttonIndex === 0) pickFromCamera();
        if (buttonIndex === 1) pickFromGallery();
      }
    );
  };

  const pickFromCamera = async () => {
    try {
      // 先请求相机权限
      const hasPermission = await requestCameraPermission();
      if (!hasPermission) {
        return;
      }

      setImageLoading(true);
      const image = await ImageCropPicker.openCamera({
        width: 800,
        height: 800,
        cropping: true,
        cropperCircleOverlay: false,
        compressImageQuality: 0.8,
        mediaType: 'photo',
        cropperToolbarTitle: '裁剪图片',
        forceJpg: true,
      });
      handleImagePicked(image);
    } catch (e) {
      // 用户取消不提示
    } finally {
      setImageLoading(false);
    }
  };

  const pickFromGallery = async () => {
    try {
      // 先请求存储权限
      const hasPermission = await requestStoragePermission();
      if (!hasPermission) {
        return;
      }

      setImageLoading(true);
      const image = await ImageCropPicker.openPicker({
        width: 800,
        height: 800,
        cropping: true,
        cropperCircleOverlay: false,
        compressImageQuality: 0.8,
        mediaType: 'photo',
        cropperToolbarTitle: '裁剪图片',
        forceJpg: true,
      });
      handleImagePicked(image);
    } catch (e) {
      // 用户取消不提示
    } finally {
      setImageLoading(false);
    }
  };

  const handleImagePicked = async (image: any) => {
    try {
      console.log('🖼️ 开始处理图片:', image);
      console.log('📁 原始图片路径:', image.path);
      
      // 生成唯一文件名
      const timestamp = Date.now();
      const fileName = `card_${timestamp}.jpg`;
      
      // 保存到外部存储的公共图片目录
      const externalDir = `${RNFS.ExternalDirectoryPath}/golang_data`;
      const cardsDir = `${externalDir}/cards`;
      const destPath = `${cardsDir}/${fileName}`;
      
      console.log('📁 外部存储目录:', externalDir);
      console.log('📁 卡片目录:', cardsDir);
      console.log('📁 目标文件路径:', destPath);
      
      // 确保目录存在
      const externalDirExists = await RNFS.exists(externalDir);
      console.log('📁 外部存储目录是否存在:', externalDirExists);
      if (!externalDirExists) {
        console.log('📁 创建外部存储目录...');
        await RNFS.mkdir(externalDir);
      }
      
      const cardsDirExists = await RNFS.exists(cardsDir);
      console.log('📁 卡片目录是否存在:', cardsDirExists);
      if (!cardsDirExists) {
        console.log('📁 创建卡片目录...');
        await RNFS.mkdir(cardsDir);
      }
      
      // 复制图片文件
      console.log('📁 开始复制图片文件...');
      await RNFS.copyFile(image.path, destPath);
      console.log('✅ 图片文件复制成功');
      
      // 验证文件是否真的保存了
      const fileExists = await RNFS.exists(destPath);
      console.log('📁 验证文件是否存在:', fileExists);
      
      if (fileExists) {
        const fileStats = await RNFS.stat(destPath);
        console.log('📁 文件统计信息:', fileStats);
      }
      
      const imagePath = `cards/${fileName}`;
      setImageUri(imagePath);
      console.log('✅ 图片保存成功:', imagePath);
      console.log('📁 图片完整路径:', destPath);
    } catch (error) {
      console.error('❌ 保存图片失败:', error);
      Alert.alert('错误', '保存图片失败');
    }
  };

  const handleCancel = () => {
    if (title || backText || imageUri) {
      Alert.alert('确认', '确定要取消编辑吗？未保存的内容将丢失。', [
        { text: '继续编辑', style: 'cancel' },
        { text: '确定取消', onPress: onCancel },
      ]);
    } else {
      onCancel();
    }
  };

  const save = () => {
    if (!title.trim()) {
      Alert.alert('错误', '请输入卡片标题');
      return;
    }
    if (!backText.trim()) {
      Alert.alert('错误', '请输入卡片文字');
      return;
    }
    if (!imageUri) {
      Alert.alert('错误', '请选择卡片图片');
      return;
    }
    const cardData = {
      title: title.trim(),
      back_text: backText.trim(),
      front_image: imageUri,
    };
    console.log('CardEditor handleSave 即将保存卡片，数据:', cardData);
    onSave(cardData);
  };

  useImperativeHandle(ref, () => ({ save }));

  const getImageUrl = (path: string) => {
    if (path.startsWith('http')) {
      return path;
    } else {
      const url = `https://127.0.0.1:8553/api/images/${path}`;
      console.log('图片 URL:', url);
      return url;
    }
  };

  return (
    <View style={editorStyles.container}>
      <View style={editorStyles.content}>
        {/* 图片选择 */}
        <View style={editorStyles.imageSection}>
          <Text style={editorStyles.label}>卡片图片</Text>
          <TouchableOpacity
            style={editorStyles.imageContainer}
            onPress={selectImage}
            activeOpacity={0.8}
            disabled={imageLoading}
          >
            {imageUri ? (
              <SecureImageView
                source={{ uri: getImageUrl(imageUri) }}
                style={editorStyles.image}
              />
            ) : (
              <View style={editorStyles.imagePlaceholder}>
                {imageLoading ? (
                  <ActivityIndicator size="large" color="#4a90e2" />
                ) : (
                  <Text style={editorStyles.imagePlaceholderText}>点击选择图片</Text>
                )}
              </View>
            )}
          </TouchableOpacity>
        </View>
        {/* 标题输入 */}
        <View style={editorStyles.inputSection}>
          <Text style={editorStyles.label}>卡片标题</Text>
          <TextInput
            style={editorStyles.input}
            value={title}
            onChangeText={setTitle}
            placeholder="请输入卡片标题"
            maxLength={50}
          />
        </View>
        {/* 文字输入 */}
        <View style={editorStyles.inputSection}>
          <Text style={editorStyles.label}>卡片文字</Text>
          <TextInput
            style={[editorStyles.input, { height: 80 }]}
            value={backText}
            onChangeText={setBackText}
            placeholder="请输入卡片背面文字"
            multiline
            maxLength={200}
          />
        </View>
        
        {/* 试听按钮 */}
        <View style={editorStyles.previewSection}>
          <TouchableOpacity
            style={[
              editorStyles.previewButton,
              (isPlaying || isSynthesizing) && editorStyles.previewButtonDisabled
            ]}
            onPress={handlePreviewAudio}
            disabled={isPlaying || isSynthesizing}
          >
            {isSynthesizing ? (
              <ActivityIndicator size="small" color="#ffffff" />
            ) : isPlaying ? (
              <Text style={editorStyles.previewButtonText}>停止播放</Text>
            ) : (
              <Text style={editorStyles.previewButtonText}>试听音频</Text>
            )}
          </TouchableOpacity>
          <Text style={editorStyles.previewHint}>
            {isSynthesizing ? '正在合成音频...' : 
             isPlaying ? '正在播放音频...' : 
             '点击试听标题和文字的语音效果'}
          </Text>
        </View>
      </View>
      {/* 底部取消按钮已移除 */}
    </View>
  );
});

// 检查音频文件是否存在（AddCardScreen级别）
const checkAudioFileExists = async (audioPath: string): Promise<boolean> => {
  try {
    if (!audioPath) return false;
    
    // 构建完整路径（使用内部存储）
    const fullPath = `${RNFS.DocumentDirectoryPath}/${audioPath}`;
    const exists = await RNFS.exists(fullPath);
    console.log('📁 检查音频文件是否存在:', fullPath, exists);
    return exists;
  } catch (error) {
    console.error('❌ 检查音频文件失败:', error);
    return false;
  }
};

// AddCardScreen 主体
const AddCardScreen: React.FC<{ onCardAdded?: (card: any) => void }> = ({ onCardAdded }) => {
  const [saving, setSaving] = useState(false);
  const navigation = useNavigation();
  const route = useRoute();
  const editorRef = useRef<CardEditorRef>(null);
  // 获取 card 参数 - 使用更可靠的方式
  const card = (route.params as any)?.card;
  
  // 调试日志和TTS配置检查
  useEffect(() => {
    console.log('🔍 AddCardScreen 路由参数:', route.params);
    console.log('🔍 AddCardScreen card 参数:', card);
    if (card) {
      console.log('🔍 编辑模式 - 卡片ID:', card.id);
      console.log('🔍 编辑模式 - 卡片标题:', card.title);
    } else {
      console.log('🔍 新建模式');
    }

    // 检查TTS配置
    checkTTSConfig();
  }, [route.params, card]);

  // 格式化TTS错误信息
  const formatTTSError = (error: any): string => {
    let errorMessage = '语音合成失败';
    
    // 提取错误信息
    if (error && typeof error === 'object') {
      if (error.message) {
        errorMessage += `: ${error.message}`;
      } else if (error.toString) {
        errorMessage += `: ${error.toString()}`;
      }
    } else if (typeof error === 'string') {
      errorMessage += `: ${error}`;
    }
    
    // 添加检查建议
    errorMessage += '\n\n请检查：\n1. appid 和 token 是否正确\n2. 网络连接是否正常\n3. 豆包TTS服务是否可用';
    
    return errorMessage;
  };

  // 检查TTS配置
  const checkTTSConfig = async () => {
    try {
      console.log('🔍 检查TTS配置...');
      
      // 先尝试从本地存储初始化TTS配置
      const initialized = await DouBaoTTSService.initializeTTSConfig();
      console.log('🔍 TTS配置初始化结果:', initialized);
      
      // 然后获取TTS配置
      const ttsConfig = await DouBaoTTSService.getTTSConfig();
      console.log('🔍 获取到的TTS配置:', ttsConfig);
      
      if (!ttsConfig.appid || !ttsConfig.token) {
        console.log('❌ TTS配置未设置');
        Alert.alert(
          'TTS配置未设置',
          '请先在设置中配置语音合成的appid和token，否则无法生成音频。您可以选择跳过音频生成直接保存卡片。',
          [
            { text: '取消', style: 'cancel' },
            { text: '去设置', onPress: () => {
              // 跳转到设置页面
              (navigation as any).navigate('ServerInfo');
            }},
            { text: '以后再说', onPress: () => {
              // 用户选择跳过，不做任何操作
              console.log('📝 用户选择跳过TTS配置');
            }}
          ]
        );
      } else {
        console.log('✅ TTS配置已设置');
      }
    } catch (error) {
      console.error('❌ 检查TTS配置失败:', error);
      Alert.alert('错误', '检查TTS配置失败');
    }
  };

  useLayoutEffect(() => {
    navigation.setOptions({
      title: card && card.id ? '编辑卡片' : '新建卡片',
      headerRight: () => (
        <View style={{ marginRight: 8 }}>
          <SaveButton onPress={() => editorRef.current?.save()} loading={saving} />
        </View>
      ),
    });
  }, [navigation, saving, card]);

  // 保存卡片但不包含音频信息
  const saveCardWithoutAudio = async (cardData: CreateCardRequest) => {
    try {
      setSaving(true);
      
      console.log('📝 保存卡片（跳过音频合成）');
      
      // 准备卡片数据（不包含音频信息）
      const finalCardData = {
        ...cardData,
        audio_path: '',
        audio_text: ''
      };
      
      console.log('🔍 最终卡片数据:', finalCardData);
      
      // 保存卡片
      let savedCard;
      if (card && card.id) {
        // 编辑模式：更新现有卡片
        console.log('📝 更新现有卡片，ID:', card.id);
        savedCard = await CardApiNative.updateCard(card.id, finalCardData);
        console.log('✅ 更新成功');
        Alert.alert('成功', '卡片更新成功（未包含音频）');
      } else {
        // 新建模式：创建新卡片
        console.log('➕ 创建新卡片');
        savedCard = await CardApiNative.createCard(finalCardData);
        console.log('✅ 创建成功');
        Alert.alert('成功', '卡片创建成功（未包含音频）');
      }
      
      if (!savedCard || typeof savedCard.id === 'undefined') {
        throw new Error('卡片保存失败，返回数据无效');
      }
      
      console.log('✅ 卡片保存完成:', savedCard);
      
      if (onCardAdded) onCardAdded(savedCard);
      navigation.goBack();
    } catch (error) {
      console.error('保存卡片失败:', error);
      Alert.alert('错误', '保存卡片失败');
    } finally {
      setSaving(false);
    }
  };

  const handleSaveCard = async (cardData: CreateCardRequest) => {
    try {
      setSaving(true);
      
      console.log('🔍 handleSaveCard 开始执行');
      console.log('🔍 card 参数:', card);
      console.log('🔍 cardData:', cardData);
      
      // 1. 先检测音频文字是否相同
      let textToSynthesize = `${cardData.title.trim()}。${cardData.back_text.trim()}`;
      console.log('🔍 音频文字:', textToSynthesize);
      console.log('🔍 现有音频文字:', card?.audio_text);
      
      let audioPath = '';
      let needSynthesize = true;
      
      // 检查文本是否有修改，以及音频文件是否存在
      if (card?.audio_text === textToSynthesize && card?.audio_path) {
        console.log('🔍 文本相同，检查音频文件是否存在');
        const audioExists = await checkAudioFileExists(card.audio_path);
        if (audioExists) {
          console.log('📁 文本未修改，使用现有音频文件:', card.audio_path);
          audioPath = card.audio_path;
          needSynthesize = false;
        } else {
          console.log('📁 文本相同但音频文件不存在，需要重新合成');
        }
      } else {
        console.log('📝 文本已修改或没有音频信息，需要重新合成');
      }
      
      // 2. 如果需要合成音频，先检查TTS配置并合成
      if (needSynthesize) {
        console.log('🎵 需要合成音频，检查TTS配置');
        
        // 检查TTS配置
        try {
          // 先尝试从本地存储初始化TTS配置
          const initialized = await DouBaoTTSService.initializeTTSConfig();
          console.log('🔍 TTS配置初始化结果:', initialized);
          
          // 然后获取TTS配置
          const ttsConfig = await DouBaoTTSService.getTTSConfig();
          console.log('🔍 获取到的TTS配置:', ttsConfig);
          
          if (!ttsConfig.appid || !ttsConfig.token) {
            console.log('❌ TTS配置未设置，无法保存卡片');
            Alert.alert(
              'TTS配置未设置',
              '请先在设置中配置语音合成的appid和token，否则无法生成音频。您可以选择跳过音频生成直接保存卡片。',
              [
                { text: '取消', style: 'cancel' },
                { text: '去设置', onPress: () => {
                  // 跳转到设置页面
                  (navigation as any).navigate('ServerInfo');
                }},
                { text: '以后再说', onPress: () => {
                  // 跳过音频合成，直接保存卡片
                  console.log('📝 用户选择跳过音频合成，直接保存卡片');
                  saveCardWithoutAudio(cardData);
                }}
              ]
            );
            return; // 阻止当前保存流程
          }
          console.log('✅ TTS配置已设置');
        } catch (error) {
          console.error('❌ 检查TTS配置失败:', error);
          Alert.alert('错误', '检查TTS配置失败，无法保存卡片');
          return; // 阻止保存流程
        }
        
        console.log('🎵 开始合成音频文件');
        
        // 生成音频文件路径（统一使用时间戳+随机数确保唯一性）
        const audioId = generateUniqueId();
        const audioFileName = `audio_${audioId}.mp3`;
        audioPath = `cards/${audioFileName}`;
        
        console.log('📁 音频文件路径:', audioPath);
        console.log('📝 合成文本:', textToSynthesize);
        
        try {
          // 先初始化TTS配置
          await DouBaoTTSService.initializeTTSConfig();
          
          // 调用豆包TTS合成音频
          const synthesizedAudioPath = await DouBaoTTSService.synthesizeAudio(
            textToSynthesize, 
            'doubao', 
            audioPath
          );
          console.log('✅ 音频合成成功:', synthesizedAudioPath);
        } catch (audioError) {
          console.error('❌ 音频合成失败:', audioError);
          // 音频合成失败，显示详细错误信息
          const errorMessage = formatTTSError(audioError);
          Alert.alert('语音合成失败', errorMessage, [
            { text: '取消', style: 'cancel' },
            { text: '去设置', onPress: () => {
              // 跳转到设置页面
              (navigation as any).navigate('ServerInfo');
            }},
            { text: '以后再说', onPress: () => {
              // 跳过音频合成，直接保存卡片
              console.log('📝 用户选择跳过音频合成，直接保存卡片');
              saveCardWithoutAudio(cardData);
            }}
          ]);
          return; // 阻止保存流程
        }
      }
      
      // 3. 准备完整的卡片数据（包含音频信息）
      const finalCardData = {
        ...cardData,
        audio_path: audioPath,
        audio_text: textToSynthesize
      };
      
      console.log('🔍 最终卡片数据:', finalCardData);
      
      // 4. 保存卡片
      let savedCard;
      if (card && card.id) {
        // 编辑模式：更新现有卡片
        console.log('📝 更新现有卡片，ID:', card.id);
        savedCard = await CardApiNative.updateCard(card.id, finalCardData);
        console.log('✅ 更新成功');
        Alert.alert('成功', '卡片更新成功');
      } else {
        // 新建模式：创建新卡片
        console.log('➕ 创建新卡片');
        savedCard = await CardApiNative.createCard(finalCardData);
        console.log('✅ 创建成功');
        Alert.alert('成功', '卡片创建成功');
      }
      
      if (!savedCard || typeof savedCard.id === 'undefined') {
        throw new Error('卡片保存失败，返回数据无效');
      }
      
      console.log('✅ 卡片保存完成:', savedCard);
      
      if (onCardAdded) onCardAdded(savedCard);
      navigation.goBack();
    } catch (error) {
      console.error('保存卡片失败:', error);
      Alert.alert('错误', '保存卡片失败');
    } finally {
      setSaving(false);
    }
  };

  const handleCancel = () => {
    navigation.goBack();
  };

  const handleDelete = async () => {
    if (!card || !card.id) return;
    Alert.alert(
      '确认删除',
      `确定要删除卡片“${card.title}”吗？`,
      [
        { text: '取消', style: 'cancel' },
        {
          text: '删除',
          style: 'destructive',
          onPress: async () => {
            try {
              setSaving(true);
              await CardApiNative.deleteCard(card.id);
              Alert.alert('成功', '卡片删除成功');
              navigation.goBack();
            } catch (error) {
              Alert.alert('错误', '删除卡片失败');
            } finally {
              setSaving(false);
            }
          },
        },
      ]
    );
  };

  return (
    <KeyboardAwareScrollView
      style={{ flex: 1 }}
      contentContainerStyle={{ flexGrow: 1, paddingBottom: 40 }}
      enableOnAndroid
      extraScrollHeight={40}
      keyboardShouldPersistTaps="handled"
    >
      <View style={styles.container}>
        <CardEditor 
          ref={editorRef} 
          onSave={handleSaveCard} 
          onCancel={handleCancel} 
          loading={saving} 
          card={card} 
          onTTSConfigMissing={() => (navigation as any).navigate('ServerInfo')}
        />
        {/* 编辑模式下显示删除按钮 */}
        {card && card.id && (
          <View style={styles.deleteFooter}>
            <TouchableOpacity
              style={styles.deleteButton}
              onPress={handleDelete}
              disabled={saving}
            >
              <Text style={styles.deleteButtonText}>删除</Text>
            </TouchableOpacity>
          </View>
        )}
      </View>
    </KeyboardAwareScrollView>
  );
};

const SaveButton = ({ onPress, loading }: { onPress: () => void; loading: boolean }) => (
  <TouchableOpacity onPress={onPress} disabled={loading} style={{ paddingHorizontal: 8 }}>
    {loading ? (
      <ActivityIndicator size="small" color="#4a90e2" />
    ) : (
      <Text style={{ fontSize: 16, color: '#4a90e2', fontWeight: 'bold' }}>保存</Text>
    )}
  </TouchableOpacity>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  deleteFooter: {
    padding: 20,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#eee',
  },
  deleteButton: {
    backgroundColor: '#ff6b6b',
    borderRadius: 8,
    alignItems: 'center',
    paddingVertical: 14,
  },
  deleteButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

const editorStyles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  content: {
    flex: 1,
    padding: 20,
  },
  imageSection: {
    marginBottom: 20,
  },
  label: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#333',
    marginBottom: 8,
  },
  imageContainer: {
    width: '100%',
    aspectRatio: 1, // 设置为正方形
    borderRadius: 12,
    overflow: 'hidden',
    backgroundColor: '#ffffff',
    borderWidth: 2,
    borderColor: '#e0e0e0',
    borderStyle: 'dashed',
  },
  image: {
    width: '100%',
    height: '100%',
    resizeMode: 'cover', // 确保图片填充整个正方形容器
  },
  imagePlaceholder: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  imagePlaceholderText: {
    fontSize: 16,
    color: '#999',
  },
  inputSection: {
    marginBottom: 20,
  },
  input: {
    backgroundColor: '#ffffff',
    borderWidth: 1,
    borderColor: '#e0e0e0',
    borderRadius: 8,
    paddingHorizontal: 12,
    paddingVertical: 12,
    fontSize: 16,
    color: '#333',
  },
  textArea: {
    height: 100,
    textAlignVertical: 'top',
  },
  previewSection: {
    marginBottom: 20,
    alignItems: 'center',
  },
  previewButton: {
    backgroundColor: '#4a90e2',
    borderRadius: 8,
    paddingHorizontal: 20,
    paddingVertical: 12,
    alignItems: 'center',
    marginBottom: 8,
  },
  previewButtonDisabled: {
    backgroundColor: '#cccccc',
  },
  previewButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  previewHint: {
    fontSize: 14,
    color: '#666',
    textAlign: 'center',
  },
  footer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    padding: 20,
    backgroundColor: '#ffffff',
    borderTopWidth: 1,
    borderTopColor: '#e0e0e0',
  },
  button: {
    flex: 1,
    paddingVertical: 12,
    borderRadius: 8,
    alignItems: 'center',
    marginHorizontal: 8,
  },
  cancelButton: {
    backgroundColor: '#f0f0f0',
  },
  buttonText: {
    fontSize: 16,
    color: '#4a90e2',
    fontWeight: 'bold',
  },
});

export default AddCardScreen; 